package server;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * @Authther: mrwu
 * @date:2021/3/29-03
 * @Description:server
 */
public class Myclassloader extends ClassLoader{
    //等于项目的根目录下的webapps目录
    private String loadrootpath;
    //具体项目的文件夹名称
    private String webcontext;

    public Myclassloader(String loadrootpath, String webcontext) {
        this.loadrootpath = loadrootpath;
        this.webcontext = webcontext;
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {

        try {
            //加载类的二进制文件
           byte[] classbytes = null;
           classbytes = loadclassbytes(name);
           //定义类向jvm输入字节码文件
            Class<?> aClass = defineClass(name, classbytes, 0, classbytes.length);
            return aClass;

        }catch (IOException e){
            throw new ClassNotFoundException(name);
        }
    }

    private byte[] loadclassbytes(String name) throws IOException {
        String contextpath = loadrootpath+"/"+webcontext;

        name= contextpath+name;
        String cname = name.replace(".", "/")+".class";//获取字节码文件名
        byte[] bytes = Files.readAllBytes(Paths.get(cname));
        return bytes;
    }


}
